#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions
cluster="monitoring"

create_infra $namespace
deploy_helm $namespace


desc 'install PMM Server'
platform=kubernetes
helm del --purge monitoring || :
if [ ! -z "$OPENSHIFT" ]; then
    platform=openshift
    oc create sa pmm-server
    oc adm policy add-scc-to-user privileged -z pmm-server
    if [ -n "$OPERATOR_NS" ]; then
        oc create clusterrolebinding pmm-pxc-operator-cluster-wide --clusterrole=percona-xtradb-cluster-operator --serviceaccount=$namespace:pmm-server
        oc patch clusterrole/percona-xtradb-cluster-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]' ${OPERATOR_NS:+-n $OPERATOR_NS}
    else
        oc create rolebinding pmm-pxc-operator-namespace-only --role percona-xtradb-cluster-operator --serviceaccount=$namespace:pmm-server
        oc patch role/percona-xtradb-cluster-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]'
    fi
    retry 10 60 helm install monitoring --set platform=$platform --set sa=pmm-server --set supresshttp2=false https://percona-charts.storage.googleapis.com/pmm-server-2.12.4.tgz
else
    helm install monitoring --set platform=$platform https://percona-charts.storage.googleapis.com/pmm-server-2.12.4.tgz
fi

desc 'create PXC cluster'
spinup_pxc "$cluster" "$test_dir/conf/$cluster.yml" 3 120

desc 'check if pmm-client container enabled'
compare_kubectl statefulset/$cluster-pxc
compare_kubectl statefulset/$cluster-haproxy

desc 'check mysql metrics'
get_metric_values node_boot_time_seconds $namespace-$cluster-pxc-0 admin:admin
get_metric_values mysql_global_status_uptime $namespace-$cluster-pxc-0 admin:admin

# TODO: check haproxy metrics

# wait for QAN
sleep 90

desc 'check QAN data'
get_qan20_values $cluster-pxc-0 admin:admin
if [[ -n "${OPENSHIFT}" ]]; then
    oc adm policy remove-scc-from-user privileged -z pmm-server
    if [ -n "$OPERATOR_NS" ]; then
        oc delete clusterrolebinding pmm-pxc-operator-cluster-wide
    else
        oc delete rolebinding pmm-pxc-operator-namespace-only
    fi
fi
helm delete monitoring
destroy $namespace
